package com.haixinga.commbiz.commons.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.haixinga.commbiz.commons.vo.SMSConfigVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author terrfly
 * @Date 2020/3/29 15:45
 * @Description 阿里云短信服务
 **/
public class AliyunSMSKit {

    private static final Logger logger = LoggerFactory.getLogger(AliyunSMSKit.class);


    /** 发送短信  */
    public static boolean sendSMS(String phoneNumber, String templateCode, JSONObject templateParams, SMSConfigVO smsConfigVO){

        if(smsConfigVO.getSmsSandbox()){
            return true;
        }


        DefaultProfile defaultProfile = DefaultProfile.getProfile("cn-hangzhou", smsConfigVO.getSmsAccessKeyId(), smsConfigVO.getSmsAccessSecret());
        IAcsClient client = new DefaultAcsClient(defaultProfile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("SignName", smsConfigVO.getSmsSignName());  //签名名称

        request.putQueryParameter("PhoneNumbers", phoneNumber);  //手机号
        request.putQueryParameter("TemplateCode", templateCode);  //模板Code
        request.putQueryParameter("TemplateParam", templateParams.toJSONString()); //模板对应的参数

        try {
            CommonResponse response = client.getCommonResponse(request);
            logger.info(response.getData());
        } catch (ClientException e) {
            logger.error("短信发送失败！", e);
            return false;
        }

        return true;
    }

    /** 生成短信验证 **/
    public static String genCode(SMSConfigVO smsConfigVO) {

        if (smsConfigVO.getSmsSandbox()) {
            return "111111";
        }

        //随机生成 6位数字
        return ((int)((Math.random()*9 + 1 ) * 100000) ) + "";
    }

}
